//
//  CommunityRegisterControllerViewController.m
//  homeland
//
//  Created by caesar on 14-7-25.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "CommunityRegisterControllerViewController.h"


#define INPUT_VIEW_OFFSET 100.0
@interface CommunityRegisterControllerViewController ()<UITextFieldDelegate>

@end

@implementation CommunityRegisterControllerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.streetId =@"";
    // Do any additional setup after loading the view from its nib.
    //页面背景图片
//    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background1"]];
    //不隐藏导航条
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.title = @"申请社区用户";
    //添加后退按扭和事件
    self.navigationItem.leftBarButtonItem = autoavBackButton(self, @selector(backMethod));
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"_navBar"] forBarMetrics:UIBarMetricsDefault];
    int height = iPhone5 ? 0 : 88 ;
    //生成底部按扭
    UIButton *postBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 460 - height, 320, 44)];
    [postBtn setBackgroundImage:[UIImage imageNamed:@"btnImage.png"] forState:0];
    [postBtn setTitle:@"提交" forState:0];
    [postBtn addTarget:self action:@selector(postBtnClicked) forControlEvents:64];
    
    
 
    [self.view addSubview:self.myView];
    [self.view addSubview:postBtn];
    
    
    
    _btnStreet.layer.borderWidth = 1;
    _btnStreet.layer.borderColor = [[UIColor blackColor] CGColor];
    _btnStreet.layer.cornerRadius = 5;

    _btnCommunity.layer.borderWidth = 1;
    _btnCommunity.layer.borderColor = [[UIColor blackColor] CGColor];
    _btnCommunity.layer.cornerRadius = 5;
    
    //
    _nameText.inputAccessoryView = [self getInputAccessoryView];
    _nameText.delegate = self;
    
    _addressText.inputAccessoryView = [self getInputAccessoryView];
    _addressText.delegate = self;
    
    [self loadStreetData] ;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//提交事件
- (void)postBtnClicked
{
    if ( self.streetId.length == 0) {
        [self.view makeToast:@"请选择街道" duration:3.0 position:@"center"];
        return;
    }
    NSString *name = self.nameText.text;
    if ( !name || name.length == 0) {
        [self.view makeToast:@"请输入姓名" duration:3.0 position:@"center"];
        return;
    }
    NSString *address = self.addressText.text;
    if (!address ||  address.length == 0) {
        [self.view makeToast:@"请输入地址" duration:3.0 position:@"center"];
        return;
    }
    [self postCommunitRegister];
    
}
//街道选择框事件
- (IBAction)streetSelectClicked:(id)sender {
    
    if(streetDropDown == nil) {//展开
        CGFloat f = 200;
        streetDropDown = [[NIDropDown alloc]init];
        streetDropDown = [[NIDropDown alloc]showDropDown:sender cHeight:&f nArr:self.streetList bIsSub:NO];
        streetDropDown.delegate = self;
        streetDropDown.tag = 0;
    }else {//收缩
        [streetDropDown hideDropDown:sender];
        [self rel];
    }
}
//社区选择框事件
- (IBAction)communitySelectClicked:(id)sender {
    if (self.streetId != nil) {
        if(communityDropDown == nil) {//展开
            CGFloat f = 200;
            communityDropDown = [[NIDropDown alloc]init];
            communityDropDown = [[NIDropDown alloc]showDropDown:sender cHeight:&f nArr:self.communityList bIsSub:NO];
            communityDropDown.delegate = self;
            communityDropDown.tag = 1;
        }else {//收缩
            [communityDropDown hideDropDown:sender];
            [self rel];
        }
    }
}
//选择会调用这个方法
- (void) niDropDownDelegateMethod: (NIDropDown *) sender indexPath:(NSInteger*)index{
    if (sender.tag == 0) {
        //街道点击
        DropDownEntity *dde = [self.streetList objectAtIndex:(int)index];
        self.streetId = @"";
        self.streetId = [NSString stringWithFormat:@"%@",dde.Id];
        
        self.streetName = dde.name;
        if (communityDropDown != nil) {
            [communityDropDown hideDropDown:self.btnCommunity];
        }
        //加载社区数据
        [self loadCommunitData];
    }else{
        //社区点击
        DropDownEntity *dde = [self.communityList objectAtIndex:(int)index];
        self.communityId = dde.Id;
        self.communityName = dde.name;
    }
    
    [self rel];
}
//释放单选框内存
-(void)rel{
    streetDropDown = nil;
    communityDropDown = nil;
}

//加载街道列表数据
- (void)loadStreetData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"2" forKey:@"item_type"];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:STREETSLIST customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
//        
        NSDictionary *json = [completedOperation responseJSON];
        NSArray *array = [json objectForKey:@"pageList"];
        
        
        NSMutableArray *tempArray = [NSMutableArray array];
        for(NSDictionary *nsd in array){
            DropDownEntity *dde = [DropDownEntity alloc];
            dde.Id = [nsd objectForKey:@"id"];
            dde.name = [nsd objectForKey:@"item_name"];
            [tempArray addObject:dde ];
        }
        self.streetList = tempArray;
        
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        
    }];
    [currentEngine enqueueOperation:op];
}

//加载社区列表数据
- (void)loadCommunitData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:self.streetId forKey:@"streetId"];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_FIND_COMMUNITY_BY_STREETID customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
//        
        NSDictionary *json = [completedOperation responseJSON];
        NSArray *array = [json objectForKey:@"communityParty"];
        
        NSMutableArray *tempArray = [NSMutableArray array];
        for(NSDictionary *nsd in array){
            DropDownEntity *dde = [DropDownEntity alloc];
            dde.Id = [nsd objectForKey:@"dituid"];
            dde.name = [nsd objectForKey:@"communityName"];
            [tempArray addObject:dde ];
        }
        self.communityList = tempArray;
        
        if (self.communityList != nil) {
            DropDownEntity *dde = [self.communityList objectAtIndex:0];
            [self.btnCommunity setTitle:dde.name forState:UIControlStateNormal];
            self.communityId = dde.Id;
            self.communityName = dde.name;
        }
        
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        
    }];
    [currentEngine enqueueOperation:op];
}

//提交
- (void)postCommunitRegister
{
    [self startLoadingViewWithText:@"正在提交..."];
    NSString *userId = [UserInfoService getUserInfoService].userInfo.Id;
    NSString *userName = self.nameText.text;
    NSString *address = self.addressText.text;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:self.streetId forKey:@"streetId"];
    [params setValue:userId forKey:@"userId"];
    [params setValue:userName forKey:@"userName"];
    [params setValue:address forKey:@"address"];
    [params setValue:self.streetName forKey:@"streetName"];
    [params setValue:self.communityId forKey:@"communityId"];
    [params setValue:self.communityName forKey:@"communityName"];
    
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_FIND_COMMUNITY_USER_REGISTER customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        [self stopLoadingView];
        NSDictionary *json = [completedOperation responseJSON];
        BOOL isSuccess = [[json objectForKey:@"isSuccess"]boolValue];
        NSString *message = [json objectForKey:@"message"];
        if (isSuccess) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            [self.view makeToast:message duration:3.0 position:@"center"];
        }
        
        
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        [self stopLoadingView];
        [self.view makeToast:@"请求失败" duration:2.0 position:@"center"];
    }];
    [currentEngine enqueueOperation:op];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //关闭当前页
    [self backMethod];
}

#pragma mark - Text Field Delegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y - INPUT_VIEW_OFFSET;
    self.view.frame = frame;
    [UIView commitAnimations];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y + INPUT_VIEW_OFFSET;
    self.view.frame = frame;
    [UIView commitAnimations];
}

@end
